package com.atguigu.eduorder.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.Result;
import com.atguigu.eduorder.entity.Order;
import com.atguigu.eduorder.service.OrderService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author 董万均
 * @since 2020-11-07
 */
@RestController
@RequestMapping("/eduorder/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    //生成订单信息：订单信息中有课程的信息和登录用户的信息
    @PostMapping("createOrder/{courseId}")
    public Result saveOrder(@PathVariable String courseId, HttpServletRequest request){
        //从request中获取用户的id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        //向要生成订单，判断用户是否登录
        if (StringUtils.isEmpty(memberId)){
            throw new GuliException(20001,"请登录");
        }
        //request指的是从cookie中获取用户的信息,返回订单的id
        String orderNo=orderService.createOrder(courseId,memberId);
        return Result.ok().data("orderNo",orderNo);
    }

    //通过订单id查询订单信息
    @GetMapping("getOrderInfo/{orderNo}")
    public Result getOrderInfo(@PathVariable String orderNo){
        QueryWrapper<Order> wrapper=new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        Order order = orderService.getOne(wrapper);
        return Result.ok().data("item",order);
    }

    //根据课程id和用户id查询该课程是否购买
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId,@PathVariable String memberId){
        QueryWrapper<Order> wrapper=new QueryWrapper<>();
        wrapper.eq("member_id",memberId);
        wrapper.eq("course_id",courseId);
        wrapper.eq("status",1);//1代表以及微信支付
        int count = orderService.count(wrapper);
        if (count>0){
            return true;
        }
        return false;
    }

}

